import axios from "axios";
import router from "@/router";

const baseURL = window.c.baseUrl;
const timeout = window.c.timeout;
const service = axios.create({
  baseURL,
  timeout,
});

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("token")) {
      config.headers["Authorization"] = localStorage.getItem("token");
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (Number(response.status) === 401) {
      router.push("/login");
      return;
    }
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
